<!DOCTYPE html>
<html
        lang="zh"
        xmlns:th="http://www.thymeleaf.org"
        xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
>
<head>
    <th:block th:insert="~{include :: header('设备遥测数据列表')}"/>
    <th:block th:insert="~{include :: datetimepicker-css}"/>
    <style>
        /* JSON数据显示样式 */
        .json-preview {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            padding: 8px;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>
                        <li>
                            <label>设备ID：</label>
                            <input type="text" name="deviceId" placeholder="请输入设备ID" />
                        </li>
                        <li>
                            <label>开始时间：</label>
                            <div class="input-group date">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                <input type="text" class="form-control" name="params[beginTime]" id="beginTime" placeholder="开始时间" readonly />
                            </div>
                        </li>
                        <li>
                            <label>结束时间：</label>
                            <div class="input-group date">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                <input type="text" class="form-control" name="params[endTime]" id="endTime" placeholder="结束时间" readonly />
                            </div>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()">
                                <i class="fa fa-search"></i>&nbsp;搜索
                            </a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()">
                                <i class="fa fa-refresh"></i>&nbsp;重置
                            </a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
            <a class="btn btn-warning" onclick="$.table.exportExcel()" shiro:hasPermission="deviceManager:telemetry:export">
                <i class="fa fa-download"></i> 导出
            </a>
            <a class="btn btn-danger" onclick="clearTelemetryData()" shiro:hasPermission="deviceManager:telemetry:clear">
                <i class="fa fa-trash"></i> 清空数据
            </a>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>

<th:block th:insert="~{include :: footer}" />
<th:block th:insert="~{include :: datetimepicker-js}"/>
<script th:inline="javascript">
    var detailFlag = [[${@permission.hasPermi('deviceManager:telemetry:detail')}]];
    var removeFlag = [[${@permission.hasPermi('deviceManager:telemetry:remove')}]];
    var clearFlag = [[${@permission.hasPermi('deviceManager:telemetry:clear')}]];
    var prefix = ctx + "deviceManager/telemetry";

    $(function () {
        var options = {
            url: prefix + "/list",
            removeUrl: prefix + "/remove",
            exportUrl: prefix + "/export",
            modalName: "设备遥测数据",
            uniqueId: 'id',
            columns: [{
                checkbox: true
            },
                {
                    field: 'id',
                    title: '记录ID',
                    visible: false
                },
                {
                    field: 'deviceId',
                    title: '设备ID',
                    sortable: true
                },
                {
                    field: 'data',
                    title: '遥测数据',
                    formatter: function (value, row, index) {
                        if (!value || typeof value !== 'string') {
                            return value || '';
                        }
                         
                        try {
                            // 尝试解析JSON字符串
                            var parsedData = JSON.parse(value);
                            // 将解析后的数据转换回字符串
                            var jsonStr = JSON.stringify(parsedData, null, 2);
                            // 去除转义字符
                            jsonStr = jsonStr.replace(/\\r\\n/g, '').replace(/\\n/g, '').replace(/\\t/g, '');
                             
                            // 限制显示长度为200个字符
                            const MAX_DISPLAY_LENGTH = 200;
                            if (jsonStr.length > MAX_DISPLAY_LENGTH) {
                                // 截取前MAX_DISPLAY_LENGTH个字符并添加省略号
                                const truncatedStr = jsonStr.substring(0, MAX_DISPLAY_LENGTH) + '...';
                                return '<div class="json-preview" title="点击查看完整数据" onclick="showDetail(\'' + row.id + '\')">' + truncatedStr + '</div>';
                            } else {
                                return '<div class="json-preview">' + jsonStr + '</div>';
                            }
                        } catch (e) {
                            // 如果不是JSON字符串，直接显示并处理长字符串
                            const MAX_DISPLAY_LENGTH = 200;
                            if (value.length > MAX_DISPLAY_LENGTH) {
                                // 截取前MAX_DISPLAY_LENGTH个字符并添加省略号
                                const truncatedStr = value.substring(0, MAX_DISPLAY_LENGTH) + '...';
                                return '<div class="json-preview" title="点击查看完整数据" onclick="showDetail(\'' + row.id + '\')">' + truncatedStr + '</div>';
                            } else {
                                return '<div class="json-preview">' + value + '</div>';
                            }
                        }
                    }
                },
                {
                    field: 'receiveTime',
                    title: '接收时间',
                    sortable: true,
                    formatter: function (value, row, index) {
                        if (!value) return '';
                        try {
                            // 尝试使用框架的日期格式化函数
                            if ($.common && $.common.formatDate) {
                                return $.common.formatDate(value);
                            }
                            // 如果框架函数不存在，使用原生JS格式化
                            const date = new Date(value);
                            if (!isNaN(date.getTime())) {
                                return date.toLocaleString('zh-CN', {
                                    year: 'numeric',
                                    month: '2-digit',
                                    day: '2-digit',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    second: '2-digit'
                                });
                            }
                            return value;
                        } catch (e) {
                            return value;
                        }
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-info btn-xs ' + detailFlag + '" href="javascript:void(0)" onclick="showDetail(\'' + row.id + '\')"><i class="fa fa-eye"></i>查看</a> ');
                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);

        // 初始化日期选择器
        $('#beginTime, #endTime').datetimepicker({
            language: 'zh-CN',
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            minView: 2,
            forceParse: 0
        });
    });

    /**
     * 查看详情
     */
    function showDetail(id) {
        $.modal.open("设备遥测数据详情", prefix + "/detail/" + id);
    }

    /**
     * 清空遥测数据
     */
    function clearTelemetryData() {
        $.modal.confirm("确定要清空所有设备遥测数据吗？此操作不可恢复！", function() {
            $.operate.post(prefix + "/clear", {}, function() {
                $.table.refresh();
                $.modal.toast.success("清空成功");
            });
        });
    }
</script>
</body>
</html>
